package edu.zut.cn.service.Impl;

import edu.zut.cn.domain.ResponseResult;
import edu.zut.cn.domain.entity.LoginUser;
import edu.zut.cn.domain.entity.User;
import edu.zut.cn.enums.CodeEnum;
import edu.zut.cn.service.LoginService;
import edu.zut.cn.utils.JwtUtil;
import edu.zut.cn.utils.RedisUtil;
import edu.zut.cn.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 *  LoginServiceImpl
 *
 * @author 张小訫
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public ResponseResult Login(User user, HttpSession session) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)){
            return ResponseResult.fail(CodeEnum.LOGIN_ERROR);
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //获取userid,生成token
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //存入session，用于拦截请求或使用thymeleaf显示姓名
        String userName = loginUser.getUser().getName();
        session.setAttribute("userName",userName);
        //把用户信息存入redis
        redisUtil.set(userId,loginUser);
        //把token封装 返回
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return ResponseResult.success(CodeEnum.LOGIN_SUCCESS,jwt);
    }

    @Override
    public ResponseResult logout(HttpSession session) {
        String userId = String.valueOf(SecurityUtils.getUserId());
        //删除redis中用户信息
        redisUtil.del(userId);
        //清除浏览器session
        session.invalidate();
        return ResponseResult.success(CodeEnum.SUCCESS);
    }
}
